/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package izsla.beans;

import izsla.entities.Motorbike;
import izsla.entities.SearchCriteria;
import izsla.entities.TripUser;
import izsla.sb.UserManagementLocal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author aki
 */
public class EditUser {
    @EJB
    private UserManagementLocal um;

    private String email;
    private String phone;

    

    private String oldPassword;
    private String password;
    private String password2;

    private long bikeId;

    private String bikeType;

    private SearchCriteria searchCriteria;
    private long criteriaId;

    private String validatePassword;
    
    public EditUser() {
        searchCriteria = new SearchCriteria();
        searchCriteria.setTripUser((TripUser)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user"));
    }

    public TripUser getUser() {
	return (TripUser)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
    }

    // REQ4
    /**
     * Adds the selected bike to the user's profile and persists it.
     */
    public String onAddBike() {
	TripUser user = getUser();
	Motorbike mb = new Motorbike();
	mb.setOwner(user);
	mb.setType(bikeType);

	user.getBikes().add(mb);
	um.mergeUser(user);

	return null;
    }

    /**
     * Deletes the selected bike from the database.
     */
    public String onDeleteBike() {
	Motorbike bike = new Motorbike();
	bike.setId(bikeId);

	TripUser user = getUser();
	if(user.getBikes().contains(bike)) {
	    um.deleteBike(bike);
	    user = um.refreshUser(user);

	    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
	}
	else {
	    System.out.println("Strange thing, possible hack");
	}

	return null;
    }

    // REQ14
    /**
     * Adds a criteria to the user's profile. The user will be notified when new trip matches it.
     */
    public String onAddCriteria() {
	TripUser user = getUser();

	user.getSearchCriterias().add(searchCriteria);
	um.mergeUser(user);

	return null;
    }

    public String onDeleteCriteria() {
	SearchCriteria criteria = null;

	TripUser user = getUser();
	for(SearchCriteria sc : user.getSearchCriterias()) {
            if (sc.getId() == criteriaId) {
                criteria = sc;
                break;
            }
	}
        if(criteria != null) {
	    um.deleteCriteria(criteria);
	    user = um.refreshUser(user);

	    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
        }
	else {
	    System.out.println("Strange thing, possible hack");
	}

	return null;
    }

    /**
     * Persists current e-mail and phone number.
     */
    public String onSave() {
	TripUser user = getUser();

	user.setEmail(email);
	user.setPhoneNumber(phone);

	um.mergeUser(user);

	return null;
    }

    /**
     * Performs email validation. An e-mail is valid, iff the following sequence of characters is found in that order:
     * at least one character, an at sign, at least one character, dot, at least one english character.
     */
    public void validateEmail(FacesContext context, UIComponent component, Object input) {
	String email = (String)input;
	
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(email);

	if(!m.matches()) {
	    throw new ValidatorException(new FacesMessage("Invalid email address"));
	}
    }

    /**
     * The knowledge of the old password is checked.
     */
    public void validateOldPassword(FacesContext context, UIComponent component, Object input) {
	String pass = (String)input;
	TripUser user = getUser();
	user = um.login(user.getName(), pass);

	if(user == null) {
	    throw new ValidatorException(new FacesMessage("Invalid old password!"));
	}
    }

    /**
     * Validates the new password. A new password is valid, iff it is more than 8 characters long.
     */
    public void validateNewPassword(FacesContext context, UIComponent component, Object input) {
	String p1 = (String)input;


	if(p1 == null || p1.length() < 8) {
	    throw new ValidatorException(new FacesMessage("Password must be 8 characters long."));
	}

	validatePassword = p1;
    }

    /**
     * Checks that the retype is the same as the original password.
     */
    public void validateNewPassword2(FacesContext context, UIComponent component, Object input) {
	String p2 = (String)input;

	if(validatePassword == null || !validatePassword.equals(p2)) {
	    throw new ValidatorException(new FacesMessage("Passwords do not match!"));
	}
    }

    /**
     * Sets the new password for the user.
     */
    public String onChangePassword() {
	if(!password2.equals(password)) {
	    System.out.println("Passwords do not match.");
	    return null;
	}

	TripUser user = getUser();
	user = um.login(user.getName(), oldPassword);

	if(user == null) {
	   System.out.println("Invalid old password!");
	   return null;
	}

	um.changePassword(user, password);

	return null;
    }

    public String getBikeType() {
	return bikeType;
    }

    public void setBikeType(String bikeType) {
	this.bikeType = bikeType;
    }

    public SearchCriteria getSearchCriteria() {
        return searchCriteria;
    }

    public long getBikeId() {
	return bikeId;
    }

    public void setBikeId(long bikeId) {
	this.bikeId = bikeId;
    }

    public long getCriteriaId() {
	return criteriaId;
    }

    public void setCriteriaId(long criteriaId) {
	this.criteriaId = criteriaId;
    }

    public String getOldPassword() {
	return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
	this.oldPassword = oldPassword;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getPassword2() {
	return password2;
    }

    public void setPassword2(String password2) {
	this.password2 = password2;
    }

    public String getEmail() {
	email = getUser().getEmail();
	return email;
    }

    public void setEmail(String email) {
	this.email = email;
    }

    public String getPhone() {
	phone = getUser().getPhoneNumber();
	return phone;
    }

    // req3
    public void setPhone(String phone) {
	this.phone = phone;
    }
}
